import editForm from "../form/index.vue";
import importModal from "../form/import.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection } from "@pureadmin/utils";
import { getPage, add, update, del } from "@/api/base";
import { h, ref, toRaw, reactive, onMounted } from "vue";

export function useDevice() {
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);

  const typeOption = [
    { type: "primary", effect: "dark", value: 0, label: "智能仓" },
    { type: "info", effect: "dark", value: 1, label: "7寸固定料架" },
    { type: "success", effect: "dark", value: 2, label: "13寸固定料架" },
    { type: "warning", effect: "dark", value: 3, label: "固定货架" },
    { type: "danger", effect: "dark", value: 4, label: "防潮箱" }
  ];

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const form = reactive({
    name: "",
    code: "",
    pageIndex: pagination.currentPage,
    pageSize: pagination.pageSize
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      width: 60,
      type: "index"
    },
    {
      label: "料号",
      prop: "OriginalCode"
    },
    {
      label: "名称",
      prop: "Name"
    },
    {
      label: "制造商",
      prop: "Mader"
    },
    {
      label: "单位",
      prop: "UnitCode"
    },
    {
      label: "最小包装",
      prop: "MinPack"
    },
    {
      label: "最大盘数",
      prop: "MaxNum"
    },
    {
      label: "最少盘数",
      prop: "MinNum"
    },
    {
      label: "存储设备",
      prop: "DeviceType",
      cellRenderer: ({ row, props }) => {
        const model = typeOption.find(p => p.value == row.DeviceType);
        if (!model) return null;
        return (
          <el-tag size={props.size} type={model.type} effect={model.effect}>
            {model.label}
          </el-tag>
        );
      }
    },
    {
      label: "备注",
      prop: "Remark"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  async function handleDelete(row) {
    let result = await del("material", { id: row.Id });
    if (result.success) {
      message(`您删除了编码为${row.OriginalCode}的这条数据`, {
        type: "success"
      });
      onSearch();
    } else {
      message(result.Message, { type: "error" });
    }
  }

  async function onSearch() {
    loading.value = true;
    const { Data } = await getPage("material", toRaw(form));
    dataList.value = Data.data;
    pagination.total = Data.total;
    pagination.pageSize = Data.pageSize;
    pagination.currentPage = Data.pageIndex;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?) {
    addDialog({
      title: `${title}设备`,
      props: {
        formInline: {
          Title: title,
          Id: row?.Id ?? 0,
          Name: row?.Name ?? "",
          OriginalCode: row?.OriginalCode ?? "",
          Mader: row?.Mader ?? "",
          UnitCode: row?.UnitCode ?? "",
          MinPack: row?.MinPack ?? 0,
          DeviceType: row?.DeviceType ?? 0,
          MaxNum: row?.MaxNum ?? 0,
          MinNum: row?.MinNum ?? 0,
          Remark: row?.Remark ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        function chores() {
          message(`您${title}了编码为${curData.OriginalCode}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let result;
            // 表单规则校验通过
            if (title === "新增") {
              result = await add("material", curData);
            } else {
              result = await update("material", curData);
            }
            if (result.success) {
              chores();
            } else {
              message(result.Message, { type: "error" });
            }
          }
        });
      }
    });
  }

  function openImportDialog() {
    addDialog({
      title: "批量导入",
      width: "50%",
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      hideFooter: true,
      contentRenderer: () =>
        h(importModal, {
          onClose: () => {
            onSearch(); // 刷新表格数据
            close();
          }
        })
    });
  }

  function handleCurrentChange(val: number) {
    form.pageIndex = val;
    onSearch();
  }

  function handleSizeChange(val: number) {
    form.pageSize = val;
    onSearch();
  }

  onMounted(async () => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    typeOption,
    deviceDetection,
    onSearch,
    resetForm,
    openDialog,
    openImportDialog,
    handleDelete,
    handleCurrentChange,
    handleSizeChange
  };
}
